package com.hand.wfive.activity

import android.content.Context
import android.os.Build
import android.view.KeyEvent
import com.hand.wfive.BuildConfig
import com.hand.wfive.R
import com.hand.wfive.ad.TTAdManagerHolder
import com.hand.wfive.base.BaseActivity
import com.hand.wfive.loginAndVip.ApiConfig
import com.hand.wfive.loginAndVip.LoginConfig
import com.hand.wfive.loginAndVip.model.ChannelIdConfig
import com.hand.wfive.loginAndVip.model.PolicyInfoModel

import com.rxjava.rxlife.RxLife
import kotlinx.android.synthetic.main.activity_privacy.topBar
import kotlinx.android.synthetic.main.activity_privacy.webView
import org.jetbrains.anko.startActivity
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.asClass

class PrivacyActivity : BaseActivity() {

    companion object {
        const val ShowPolicy = 0 //隐私
        const val ShowUserAgreement = 1 //用户协议
        const val VIPRULE = 2 //购买须知

        const val ShowSDKInfoShareList = 3 // 第三方sdk列表
        const val PolicyUserInfoList = 4 // 用户资料信息
        const val PolicyUserIdCardInfo = 5 // 用户身份信息
        const val PolicyUserServiceInfo = 6 // 用户服务信息
        const val PolicyUserDeviceInfo = 7 // 用户设备信息

        @JvmStatic
        fun showRule(context: Context?, type: Int) {
            if (context == null) {
                return
            }
            context.startActivity<PrivacyActivity>("type" to type)
        }
    }

    private var mType = ShowPolicy
    private var mLoadLocalHtml = false

    override fun getContentViewId() = R.layout.activity_privacy

    override fun init() {
        topBar.addLeftBackImageButton().setOnClickListener {
            doOnBackPressed()
        }

        mType = intent.getIntExtra("type", ShowPolicy)
        webView.settings.defaultTextEncodingName = "UTF-8"
        webView.setOnPageFinishedListener {
            when (mType) {
                ShowPolicy -> if (mLoadLocalHtml) setHtmlValue()
                else -> setHtmlValue()
            }
        }
        webView.setOnKeyListener { v, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
                    webView.goBack()//后退
                    return@setOnKeyListener true
                }
            }
            return@setOnKeyListener false
        }

        when (mType) {
            ShowPolicy -> {
                topBar.setTitle("隐私政策")
                getPolicyInfo()
            }

            VIPRULE -> {
                topBar.setTitle("购买须知")
                webView.loadUrl("file:///android_asset/vip.html")
            }

            ShowSDKInfoShareList -> {
                topBar.setTitle("第三方信息共享清单")
                getPolicyInfo()
            }

            PolicyUserInfoList -> {
                topBar.setTitle("用户资料信息")
                webView.loadUrl("file:///android_asset/policy_user_info.html")
            }

            PolicyUserIdCardInfo -> {
                topBar.setTitle("用户身份信息")
                webView.loadUrl("file:///android_asset/policy_user_id_card_info.html")
            }

            PolicyUserServiceInfo -> {
                topBar.setTitle("用户服务内容信息")
                webView.loadUrl("file:///android_asset/policy_user_service_info.html")
            }

            PolicyUserDeviceInfo -> {
                topBar.setTitle("设备信息")
                webView.loadUrl("file:///android_asset/policy_user_device_info.html")
            }

            else -> {
                topBar.setTitle("用户协议")
                webView.loadUrl("file:///android_asset/user_agreement.html")
            }
        }
    }

    override fun doOnBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack()//后退
        } else {
            super.doOnBackPressed()
        }
    }

    private fun getPolicyInfo() {
        showLoading("加载中...")
        val url = if (mType == ShowSDKInfoShareList) {
            ApiConfig.getPrivateSdkInfo
        } else {
            ApiConfig.getPolicyInfo
        }
        RxHttp.postForm(url)
            .add("AppId", BuildConfig.APPLICATION_ID)
            .add("channelId", ChannelIdConfig.getValue())
            .asClass<PolicyInfoModel>()
            .to(RxLife.toMain(this))
            .subscribe({
                hideLoading()
                println("onNext: $it")
                if (it.code == ApiConfig.SUCCESSCODE) {
                    webView.loadUrl("${ApiConfig.baseUrl}${it.obj.pageUrl}")
                } else {
                    mLoadLocalHtml = true
                    loadLocalPolicy()
                }
            }, {
                hideLoading()
                mLoadLocalHtml = true
                println("onError: ${it.printStackTrace()}")
                loadLocalPolicy()
            })
    }

    private fun loadLocalPolicy() {
        if (mType == ShowSDKInfoShareList) {
            webView.loadUrl("file:///android_asset/policy_sdk_list.html")
        } else {
            webView.loadUrl("file:///android_asset/privacy_policy.html")
        }
    }

    private fun setHtmlValue() {
        webView.evaluateJavascript("setOSVersion('" + Build.VERSION.RELEASE + "')") { }
        webView.evaluateJavascript("setAppVersion('" + BuildConfig.VERSION_NAME + "')") { }
        webView.evaluateJavascript("setPhoneModel('" + Build.MODEL + "')") { }
        webView.evaluateJavascript("setPhoneBrand('" + Build.BRAND + "')") { }
        webView.evaluateJavascript("setSDKVersion('" + Build.VERSION.SDK_INT + "')") { }

        webView.evaluateJavascript("setCompany('" + getString(R.string.companyname) + "')") { }
        webView.evaluateJavascript("textModify('" + getString(R.string.app_name) + "')") { }
        webView.evaluateJavascript("setVipContent('" + LoginConfig.VIPContent + "')") { }
        if (TTAdManagerHolder.opNoticeState()) {
            webView.evaluateJavascript(
                "setNotice('6.若您不想接受个性化广告服务，您可以在【我的-个性化推荐】进行关闭管理。" +
                        "若您选择关闭，您看到的广告数量不会减少，但本产品将不再向您展示个性化广告，您看到的广告将" +
                        "可能与您的偏好相关度降低')"
            ) { }
        }
        if ("xiaomi" == getString(R.string.channel)) {
            webView.evaluateJavascript(
                "setQQ('或者添加QQ：${LoginConfig.PrivacyQQ}与我们取得联系。')"
            ) { }
        }
    }

}
